package com.ddl.service.impl;

import com.ddl.common.enums.ErrorCode;
import com.ddl.common.exception.BusinessException;
import com.ddl.enums.SmsCodeEnum;
import com.ddl.redis.RedisKey;
import com.ddl.redis.RedisService;
import com.ddl.service.SmsCodeService;
import com.ddl.util.DataUtil;
import com.ddl.util.SmsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: liyuxiang
 * @create: 2018-11-01
 */
@Service
public class SmsCodeImplService implements SmsCodeService {

    private final static Logger logger = LoggerFactory.getLogger(SmsCodeImplService.class);

    @Autowired
    private RedisService redisService;

    private static final Long ten_minute = 10 * 60L;

    @Override
    public void sendSmsCode(String mobile, String type) {
        SmsCodeEnum smsCodeEnum = SmsCodeEnum.getByValue(type);
        String value = DataUtil.getRandomStr(6);
        redisService.set(RedisKey.SMS_CODE + mobile + "_" + type, value, ten_minute);
        SmsUtils.sendSms(mobile, value, smsCodeEnum.getCode());
    }

    /**
     * 验证短信验证码
     *
     * @param key
     * @param smsCode
     */
    @Override
    public void verificationSmsCode(String key, String smsCode) {
        String value = redisService.get(key);
        if (!smsCode.equalsIgnoreCase(value)) {
            logger.error("手机号{}找回密码接口查询redis为空", key);
            throw new BusinessException(ErrorCode.ESSAGE_ERROR_M407);
        }
    }

}
